use strict;
use warnings;
use POSIX qw(strftime);
use Android;
use Try::Tiny;

local $|       = 1;
our   $VERSION = '0.03';
my    $droid   = Android->new();

my $sl4a_path = "/storage/sdcard0/sl4a/";

sub myalarm {
	my ($value, $diff, $alarm_times) = @_;
	my $now_time = time;
	my $str_time = strftime("%Y-%m-%d %H:%M:%S", localtime($now_time));
	
	my $hour = strftime("%H", localtime($now_time));
	if ($hour < 4 and $diff<1000) {
		$alarm_times = 20;
	}

	foreach my $idx (1 .. $alarm_times) {
		my $result = $droid->vibrate();
		sleep(1);
	}
	
	my $alarm_content = "TIME:$str_time;\n" . "v=$value\n" . "d=$diff\n";
	$droid->smsSend("13728733510", "$alarm_content");
}

sub log_data {
	my ($data, $filename) = @_;
	open FV,">>$sl4a_path/tmp/$filename";
	print FV $data;
}

sub list_data {
	my @filenames = @_;
	my $index = 0;
	foreach my $file (@filenames) {
		if ($index == 0) {
			print "====================log data======================\n";
		} elsif ($index == 1) {
			print "====================diff data======================\n";
		}
		$index++;
		system("/data/data/berserker.android.apps.sshdroid/home/bin/tail -n 15  $sl4a_path/tmp/$file");
	}
}

my $value = 0;
my $str_time = 0;
my $now_time = time;
my $last_time = time;
my $last_value = 0;
my $report_limit = 10;
my $print_value_interval = 20;
my $sleep_interval_wget = 60;

while (1) {
	$now_time = time;
	$str_time = strftime("%Y-%m-%d %H:%M:%S", localtime($now_time));
	my $hour = strftime("%H", localtime($now_time));
	if ((($hour>=3 and $hour<=8) or ($hour>=16 and $hour<=20)) and $value>1000) { #when is not in update time
		print "[$str_time], [sleep], [value] $value\n";
		my $tmp_time = time;
		while (time - $tmp_time < $sleep_interval_wget) {
			sleep(1);
		}
		next;
	}

	system("/data/data/berserker.android.apps.sshdroid/home/bin/wget http://202.108.37.102/list=hf_AGTD -O $sl4a_path/tmp/data.txt");
	system("/data/data/berserker.android.apps.sshdroid/home/bin/clear");
	open FV, "$sl4a_path/tmp/data.txt";
	my $data = <FV>;
	my $all_value = "";
	if ($data =~ /q_str_hf_AGTD="(.+),/) {
		$all_value = $1;
	}
	my @value_arr = split /,/,$all_value;
	if ($value_arr[0]<10000 and $value_arr[0]>3000) {
		$value = $value_arr[0];
	}
	
	if (time - $last_time > $print_value_interval) {
		$last_time = time;
		print "[$str_time], [value] $value\n";
		log_data("[$str_time], [value] $value\n", "logdata.txt");
	}
	list_data("logdata.txt","diffdata.txt");
	
	my $tmp_time = time;
	my $diff = $value - $last_value;
	if (abs($diff) > $report_limit) {
		my $alarm_times = 3;
		if ($diff > 40) {
			$alarm_times = 6;
		}
		if ($diff > 60) {
			$alarm_times = 9;
		}
		myalarm($value, $diff, $alarm_times);
		print "[$str_time], [last_value] $last_value, [new_value] $value, [diff] $diff\n";
		log_data("[$str_time], [last_value] $last_value, [new_value] $value, [diff] $diff\n", "diffdata.txt");
		$last_value = $value;
	}
	
	while (time - $tmp_time < $sleep_interval_wget) {
		sleep(1);
	}
}


